using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Collections.Specialized;

using NTTHAO.Common.BL;
using NTTHAO.Web.BL.CommonPage;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.IO;

namespace NTTHAO.CommonWeb
{
    /// <summary>
    /// Summary description for Global
    /// </summary>
    public static class WebGlobal
    {
        public static bool IsAdministratorAuth()
        {
            return HttpContext.Current.User.Identity.Name.Equals("admin", StringComparison.OrdinalIgnoreCase);
        }
        
        public static bool IsAdminUser(string userName)
        {
            AdminUser adminUserObj = new AdminUser(userName);
            return adminUserObj.Type == 0 ? true : false;
        }

        public static bool IsUser(string userName)
        {
            AdminUser adminUserObj = new AdminUser(userName);
            return adminUserObj.ID > 0 ? true : false;
        }

        public static void SignOut(HttpRequest request, HttpResponse response, HttpSessionState session) 
        {
            FormsAuthentication.SignOut();
            session.Remove("LOGGED_USER_TYPE");
            session.Remove("LOGGED_USER_ID");
            session.Remove("LOGGED_USER_NAME");
            LanguageUtility.ReloadLanguage(request, response, session);
        }

        public static void IncreasePageView()
        {
            try
            {
                ConfigValues value = new ConfigValues(Constant.PAGE_VIEW_NAME);
                if (value.ID > 0)
                {
                    try
                    {
                        value.Value = (Int32.Parse(value.Value.Trim()) + 1).ToString();
                    }
                    catch (Exception)
                    {
                        value.Value = "1";
                    }

                    value.Update();
                }
                else
                {
                    value.Name = Constant.PAGE_VIEW_NAME;
                    value.Value = "1";
                    value.Type = 0;

                    value.Insert();
                }
                
            }
            catch (Exception)
            {
            }
        }

        public static int PageView()
        {
            try
            {
                ConfigValues value = new ConfigValues(Constant.PAGE_VIEW_NAME);
                if (value.ID > 0)
                {
                    return Int32.Parse(value.Value.Trim());
                }
            }
            catch (Exception)
            {
            }
            return 1;
        }

        public static int Online()
        {
            try
            {
                ConfigValues value = new ConfigValues(Constant.ONLINE_NAME);
                if (value.ID > 0)
                {
                    return Int32.Parse(value.Value.Trim());
                }
            }
            catch (Exception)
            {
            }
            return 1;
        }

        public static CommonSite GetSite(HttpSessionState session)
        {
            try
            {
                if (session != null && session[Constant.SITE_SESSION] != null)
                {
                    return ((CommonSite)session[Constant.SITE_SESSION]);
                }
                else
                {
                    CommonSite site = CommonSite.GetDefaultSite();
                    if (session != null)
                    {
                        session.Add(Constant.SITE_SESSION, site);
                    }
                    return site;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static CommonSite GetSite()
        {
            return WebGlobal.GetSite(HttpContext.Current.Session);
        }

        public static void SendMail(MailMessage mm)
        {
            SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
            mailClient.EnableSsl = true;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.UseDefaultCredentials = false;
            mailClient.Timeout = 50000;
            //mailClient.Credentials = new NetworkCredential("contact.transcom.vn@gmail.com", "123456789xyz");
            mailClient.Credentials = new NetworkCredential("contactus.vn@gmail.com", "123456789xyz");

            mm.From = new MailAddress(mm.From.Address, "Web Contact", System.Text.Encoding.UTF8);

            mailClient.Send(mm);
        }

        public static void UserOnline()
        {
            try
            {
                ConfigValues value = new ConfigValues(Constant.ONLINE_NAME);
                if (value.ID > 0)
                {
                    try
                    {
                        value.Value = (Int32.Parse(value.Value.Trim()) + 1).ToString();
                    }
                    catch (Exception)
                    {
                        value.Value = "1";
                    }

                    value.Update();
                }
                else
                {
                    value.Name = Constant.ONLINE_NAME;
                    value.Value = "1";
                    value.Type = 0;

                    value.Insert();
                }
            }
            catch (Exception)
            {
            }
        }

        public static void UserOffline()
        {
            try
            {
                ConfigValues value = new ConfigValues(Constant.ONLINE_NAME);
                if (value.ID > 0)
                {
                    try
                    {
                        int online = Int32.Parse(value.Value.Trim());
                        if (online > 0)
                        {
                            online--;
                        }
                        value.Value = online.ToString();
                    }
                    catch (Exception)
                    {
                        value.Value = "0";
                    }

                    value.Update();
                }
            }
            catch (Exception)
            {
            }
        }

        public static void SessionStart(HttpSessionState session)
        {
            try
            {
                SessionEntity sessionEnt = new SessionEntity();
                sessionEnt.SesstionID = session.SessionID;
                sessionEnt.Action = 1;
                sessionEnt.Request = HttpContext.Current.Request.UserHostAddress;
                sessionEnt.InsertTime = DateTime.Now;
                sessionEnt.Insert();
            }
            catch { }
        }

        public static void SessionEnd(HttpSessionState session)
        {
            try
            {
                SessionEntity sessionEnt = new SessionEntity();
                sessionEnt.SesstionID = session.SessionID;
                sessionEnt.Action = 2;
                sessionEnt.Request = HttpContext.Current.Request.UserHostAddress;
                sessionEnt.InsertTime = DateTime.Now;
                sessionEnt.Insert();
            }
            catch { }
        }

        public static string MD5String(string str)
        {
            byte[] hashedDataBytes;
            UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(str));

            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < hashedDataBytes.Length; i++)
            {
                sBuilder.Append(hashedDataBytes[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }

        public static string GetClientIpAddress(HttpRequest request)
        {
            try
            {
                string userHostAddress = request.UserHostAddress;

                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                IPAddress.Parse(userHostAddress);

                string xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;

                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                string[] publicForwardingIps = xForwardedFor.Split(',');
                foreach (string item in publicForwardingIps)
                {
                    if (!IsPrivateIpAddress(item))
                    {
                        return item;
                    }
                }

                // If we found any, return the last one, otherwise return the user host address
                return userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }

        private static bool IsPrivateIpAddress(string ipAddress)
        {
            // http://en.wikipedia.org/wiki/Private_network
            // Private IP Addresses are: 
            //  24-bit block: 10.0.0.0 through 10.255.255.255
            //  20-bit block: 172.16.0.0 through 172.31.255.255
            //  16-bit block: 192.168.0.0 through 192.168.255.255
            //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)

            IPAddress ip = IPAddress.Parse(ipAddress);
            byte[] octets = ip.GetAddressBytes();

            bool is24BitBlock = octets[0] == 10;
            if (is24BitBlock) return true; // Return to prevent further processing

            bool is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
            if (is20BitBlock) return true; // Return to prevent further processing

            bool is16BitBlock = octets[0] == 192 && octets[1] == 168;
            if (is16BitBlock) return true; // Return to prevent further processing

            bool isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
            return isLinkLocalAddress;
        }

        public static string GetPlainText(string html)
        {
            html = Regex.Replace(html, @"<[^<|>]+?>", " ", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\n", " ");
            html = Regex.Replace(html, @"\r", "");
            html = Regex.Replace(html, @"\s+", " ").Trim();
            return html;
        }

        public static void EmptyVirtualFolder(string virtualPath, bool recursive)
        {
            WebGlobal.EmptyFolder(HttpContext.Current.Server.MapPath(virtualPath), recursive);
        }

        public static void EmptyFolder(string folderPath, bool recursive)
        {
            if (!Directory.Exists(folderPath))
            {
                return;
            }
            string[] files = Directory.GetFiles(folderPath);
            if (files != null)
            {
                foreach (string file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch { }
                }
            }

            if (recursive)
            {
                string[] subFolders = Directory.GetDirectories(folderPath);
                if (subFolders != null)
                {
                    foreach (string folder in subFolders)
                    {
                        WebGlobal.EmptyVirtualFolder(folder, recursive);
                    }
                }
            }
        }

        public static string ReadVirtualFileAsText(string virtualFilePath)
        {
            return WebGlobal.ReadFileAsText(HttpContext.Current.Server.MapPath(virtualFilePath));
        }

        public static string ReadFileAsText(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return null;
            }
            return File.ReadAllText(filePath, Encoding.UTF8);
        }

        public static string JsonEncode(string json)
        {
            return json.Replace(@"\", @"\\").Replace(Environment.NewLine, @"\n").Replace("\t", "").Replace("\"", "\\\"");
        }

        public static string GetRawUrlWithWWW(HttpRequest request)
        {
            return "http://www." + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString())) + (request.RawUrl.IndexOf("?") > 0 ? request.RawUrl.Split(new string[] {"?"}, StringSplitOptions.RemoveEmptyEntries)[0] : request.RawUrl);
        }

        public static string GetRawUrlWithoutWWW(HttpRequest request)
        {
            return "http://" + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString())) + (request.RawUrl.IndexOf("?") > 0 ? request.RawUrl.Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0] : request.RawUrl);
        }

        public static string GetFullUrlWithWWW(string virtualUrl)
        {
            HttpRequest request = HttpContext.Current.Request;
            return "http://www." + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString())) + (virtualUrl.StartsWith("/") ? virtualUrl : ("/" + virtualUrl));
        }

        public static string GetFullUrlWithoutWWW(string virtualUrl)
        {
            HttpRequest request = HttpContext.Current.Request;
            return "http://" + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString())) + (virtualUrl.StartsWith("/") ? virtualUrl : ("/" + virtualUrl));
        }

        public static string GetHost()
        {
            HttpRequest request = HttpContext.Current.Request;
            return "http://" + (request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString()));
        }

        public static string GetHostWithWWW()
        {
            HttpRequest request = HttpContext.Current.Request;
            return "http://www." + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString()));
        }

        public static string GetHostWithoutWWW()
        {
            HttpRequest request = HttpContext.Current.Request;
            return "http://" + (request.Url.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? request.Url.Host.Substring(4) : request.Url.Host) + (request.Url.Port == 80 ? "" : (":" + request.Url.Port.ToString()));
        }

        public static string UrlCombine(string path1, string path2)
        {
            return path1.Trim().TrimEnd('/') + "/" + path2.Trim().TrimStart('/');
        }

        public static string GetContentURL(string menuPath, int contentID, string contentURLText)
        {
            return "/" + CommonMenu.GetUrlPath(menuPath) + "/" + contentURLText + "_" + contentID.ToString("0") + ".html";
        }
    }
}